package com.csw.android.dev_utils.utils

import android.provider.Settings
import android.view.Window
import androidx.lifecycle.MutableLiveData
import com.csw.android.dev_utils.SDK
import java.lang.Integer.min
import kotlin.math.max

object BrightnessManager {

    /**
     * 屏幕亮度值[1,100]
     */
    val brightness = object : MutableLiveData<Int>() {

        override fun postValue(value: Int) {
            super.postValue(max(1, min(value, 100)))
        }

        override fun setValue(value: Int) {
            super.setValue(max(1, min(value, 100)))
        }

        override fun getValue(): Int? {
            syncBrightness(super.getValue())
            return super.getValue()
        }

    }

    private fun syncBrightness(appValue: Int?) {
        val currValue = getSystemValue(AppUtils.resumedActivity?.get()?.window)
        if (appValue != currValue) {
            brightness.value = currValue
        }
    }

    init {
        AppUtils.appInForeground.observeForever {
            it ?: return@observeForever
            if (it) {
                val currValue = brightness.value
            }
        }
        brightness.observeForever {currValue->
            //同步系统亮度
            val window = AppUtils.resumedActivity?.get()?.window
            if (getSystemValue(window) != currValue) {
                window?.run {
                    val lp = attributes
                    lp.screenBrightness = currValue / 100f
                    attributes = lp
                }
            }
        }
    }

    /**
     * 获取亮度值
     */
    private fun getSystemValue(window: Window?): Int {
        var brightness = -1f
        //读取窗口亮度
        window?.let {
            brightness = it.attributes.screenBrightness
        }
        if (brightness < 0) {
            //读不到窗口亮度，我们读取系统亮度
            try {
                val brightness255 = Settings.System.getInt(
                    SDK.getApplication().contentResolver,
                    Settings.System.SCREEN_BRIGHTNESS
                )
                val isAutoBrightness = Settings.System.getInt(
                    SDK.getApplication().contentResolver,
                    Settings.System.SCREEN_BRIGHTNESS_MODE
                ) == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC
                if (isAutoBrightness && brightness255 <= 0) {
                    //在自动亮度模式下，没有获取到亮度值
                    brightness = -1f
                } else {
                    brightness = brightness255 / 255f
                }
            } catch (e: Exception) {
                brightness = -1f
            }
        }
        var value = (brightness * 100).toInt()
        if (value <= 0) {
            //还是没有亮度值
            val currValue = this@BrightnessManager.brightness.value ?: -1
            value = if (currValue >= 0) currValue else 50
        }
        return value
    }
}